package utils

import (
	"strconv"
	"strings"
)

// 判断字符串是否在字符串切片中, 返回bool
func InStringSlice(s string, ss []string) bool {
	for _, v := range ss {
		if v == s {
			return true
		}
	}
	return false
}

// 判断任意类型是否在切片中, 返回bool
func InSlice(s interface{}, ss []interface{}) bool {
	for _, v := range ss {
		if v == s {
			return true
		}
	}
	return false
}

// 将int64切片转换为字符串
func Int64SliceToString(s []int64, delimiter string) string {
	strs := make([]string, len(s))
	for i, v := range s {
		strs[i] = strconv.FormatInt(v, 10)
	}
	return "[" + strings.Join(strs, delimiter) + "]"
}

// 从redis读取的bitmap值(字符串)转换为int64列表
func StringToInt64Slice(data string) []int64 {
	// 遍历每个字节
	var indexes []int64
	for i := 0; i < len(data); i++ {
		for j := 7; j >= 0; j-- {
			// 检查当前位是否为 1
			if (data[i] & (1 << j)) != 0 {
				indexes = append(indexes, int64(8*i+(7-j)))
			}
		}
	}

	return indexes
}

// 去除切片中的重复元素 []int{1, 2, 3, 4, 5, 1, 2, 3, 4, 5} -> []int{1, 2, 3, 4, 5}
func RemoveDuplicatesInt(elements []int) []int {
	encountered := map[int]bool{}
	result := []int{}

	for _, v := range elements {
		if !encountered[v] {
			encountered[v] = true
			result = append(result, v)
		}
	}

	return result
}

// 去除切片中的重复元素 []int64{1, 2, 3, 4, 5, 1, 2, 3, 4, 5} -> []int64{1, 2, 3, 4, 5}
func RemoveDuplicatesInt64(elements []int64) []int64 {
	encountered := map[int64]bool{}
	result := []int64{}

	for _, v := range elements {
		if !encountered[v] {
			encountered[v] = true
			result = append(result, v)
		}
	}

	return result
}

// 去除切片中的重复元素 []string{"a", "b", "c", "d", "e", "a", "b", "c", "d", "e"} -> []string{"a", "b", "c", "d", "e"}
func RemoveDuplicatesString(elements []string) []string {
	encountered := map[string]bool{}
	result := []string{}

	for _, v := range elements {
		if !encountered[v] {
			encountered[v] = true
			result = append(result, v)
		}
	}

	return result
}

// 从切片中删除另一个切片中的元素
func RemoveElements(original []int64, toRemove []int64) []int64 {
	toRemoveMap := make(map[int64]bool)
	for _, item := range toRemove {
		toRemoveMap[item] = true
	}

	result := []int64{}
	for _, item := range original {
		if _, exist := toRemoveMap[item]; !exist {
			result = append(result, item)
		}
	}
	return result
}

// 找出两个 int64 类型切片的交集
func Int64SliceIntersection(slice1 []int64, slice2 []int64) []int64 {
	// 使用 map 来记录 slice1 中元素的存在
	existMap := make(map[int64]bool)
	for _, v := range slice1 {
		existMap[v] = true
	}

	// 检查 slice2 中的每个元素，如果在 map 中存在，将其添加到交集切片中
	var intersection []int64
	for _, v := range slice2 {
		if existMap[v] {
			intersection = append(intersection, v)
		}
	}

	return intersection
}
